//go:build windows
// +build windows

package util

import (
	"context"
	"runtime"
	"strconv"
	"strings"

	"fmt"

	"github.com/chromedp/cdproto/cdp"
	"github.com/chromedp/cdproto/dom"
	"github.com/chromedp/cdproto/input"

	//"github.com/chromedp/cdproto/runtime"
	"github.com/chromedp/chromedp"
	"github.com/go-vgo/robotgo"
)

// chromedp.Run(ctx, DragElement('#test_ele'))
func DragElement(sel interface{}, ctx context.Context) {
	// chromedp.Run(ctx, chromedp.QueryAfter(sel, func(ctx context.Context, id runtime.ExecutionContextID, node ...*cdp.Node) error {
	// 	fmt.Println("Node", sel, len(node))
	// 	if len(node) == 0 {
	// 		return fmt.Errorf("找不到相关 Node")
	// 	}
	// 	fmt.Println("移动Node", sel)
	// 	return MouseDragNode(node[0]).Do(ctx)
	// },
	// 	chromedp.AtLeast(0),
	// 	chromedp.ByQuery))
	if runtime.GOOS == "android" {
		return
	}
	fmt.Println("Node", sel)
	pos := strings.Split(sel.(string), ",")
	startX, err := strconv.Atoi(pos[0])
	if err != nil {
		fmt.Println(err)
	}
	if startX == 0 {
		startX = 356
	}
	startY := 0
	if len(pos) > 1 {
		startY, err = strconv.Atoi(pos[1])
		if err != nil {
			fmt.Println(err)
		}
		if startY == 0 {
			startY = 500
		}
	}

	robotgo.MoveMouse(startX, startY)
	robotgo.MouseDown()
	robotgo.MoveMouseSmooth(startX+400, startY+2)
	robotgo.MouseUp()
}

func MouseDragNode(n *cdp.Node) chromedp.ActionFunc {
	return func(ctx context.Context) error {
		boxes, err := dom.GetContentQuads().WithNodeID(n.NodeID).Do(ctx)
		if err != nil {
			return err
		}

		box := boxes[0]
		c := len(box)
		if c%2 != 0 || c < 1 {
			return chromedp.ErrInvalidDimensions
		}

		var x, y float64
		for i := 0; i < c; i += 2 {
			x += box[i]
			y += box[i+1]
		}
		x /= float64(c / 2)
		y /= float64(c / 2)

		p := &input.DispatchMouseEventParams{
			Type:       input.MousePressed,
			X:          x,
			Y:          y,
			Button:     input.Left,
			ClickCount: 1,
		}

		if err := p.Do(ctx); err != nil {
			return err
		}

		// Mouse Move
		p.Type = input.MouseMoved
		p.X = x + 500

		if err := p.Do(ctx); err != nil {
			return err
		}

		p.Type = input.MouseReleased
		return p.Do(ctx)
	}
}
